package threads.demo01;

import java.util.concurrent.TimeUnit;

/**
 * 死锁可以通过很多工具检测处理，例如：
 * 1. jps + jstack
 * 2. jmc
 * 3. jvisualvm
 * ...
 */
public class DeadLockDemo {
    public static void main(String[] args) throws InterruptedException {
        DealThread task = new DealThread();
        Thread thread = new Thread(task);
        thread.start();

        TimeUnit.SECONDS.sleep(1);

        task.setDirection(true);
        Thread thread2 = new Thread(task);
        thread2.start();
    }
}


class DealThread implements Runnable {

    private boolean direction = false;
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void setDirection(boolean direction) {
        this.direction = direction;
    }

    @Override
    public void run() {
        if (direction) {
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + "已经获取 lock1 的锁, 等待获取 lock2 的锁");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "又获取到 lock2 的锁, 执行结束");
                }
            }
        } else {
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "已经获取 lock2 的锁, 等待获取 lock1 的锁");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "又获取到 lock1 的锁, 执行结束");
                }
            }
        }
    }
}